package com.mmp.main.servlet.report;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mmp.common.servlet.BasicServlet;
import com.mmp.main.entity.HospitalDevice;
import com.mmp.main.util.Default;
import com.mmp.main.util.Enums;
import com.mmp.main.util.WebUtil;

public class ViewDevicesNeedPPMVisit extends BasicServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		int siteId = getSessionSiteId(request);
		int locationId = getSessionLocationId(request);
		int month = WebUtil.getParamValueAsInteger(request, "month", 0);
		int category = WebUtil.getParamValueAsInteger(request, "category", 0);

		Map<Integer, Object> map = new HashMap<Integer, Object>();
		int i = 1;

		String jpql = "SELECT h FROM HospitalDevice h WHERE h.status NOT IN("
				+ Enums.DEVICE_STATUS.SCRAPPED.getStatus() + "," + Enums.DEVICE_STATUS.TRANSFERRED.getStatus()
				+ ") AND h.site.id = " + siteId;

		if (locationId != 0) {
			jpql += " AND h.hospital.id = ?";
			map.put(i++, locationId);
		}

		if (month != 0) {
			jpql += " AND h.pmVisitsMonths LIKE ?";
			map.put(i++, "%" + Default.MULTIVALUE_SEPARATOR + month + Default.MULTIVALUE_SEPARATOR + "%");
		}

		if (category != 0) {
			jpql += " AND h.category.id = ?";
			map.put(i++, category);
		}

		jpql += " ORDER BY h.hospital.id, h.hospitalDepartment.name, h.category.id, h.name";

		List<HospitalDevice> deviceList = dbQueryManager.queryJPQL(jpql, map, HospitalDevice.class);

		if (deviceList == null || deviceList.isEmpty()) {
			announceErorrMessage(request, response, "لا توجد أجهزة  من الفئة المدخلة تحتاج زيارة وقائية خلال شهر "
					+ Enums.YEAR_MONTHS.getTextById("" + month));
			return;
		}

		HashMap params = new HashMap();
		params.put(Default.REPORT_TITLE_PARAM_NAME, Enums.REPORT_TITLE.DEVICES_NEED_PPM_VISIT.getReportTitle());
		params.put("deviceList", deviceList);
		params.put("month", Integer.valueOf(month));
		viewPDFReport("rt8.jasper", null, params, request, response);
	}
}
